<?php
class UCModPanel
{
	private $_apcttl;
	private $_mcttl;
	private $_included = false;
	private $_userid = 0;
	private $_store = null;

	function __construct($userid = 0){
		 if( !$this->_included ) {
			require_once(dirname(__FILE__).'/../../libraries/UCLibPDOFactory.php');
			require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');
			require_once(dirname(__FILE__).'/../../libraries/UCLibStat.php');
			require_once(dirname(__FILE__).'/../../config/UCConfStore.php');
			require_once(dirname(__FILE__).'/../../models/store/UCModStore.php');

		    $this->_included = true;
		 }

		if(!is_numeric($userid))
			return false;

		$this->_store = UCModStore::getInstance();
		$this->_userid = $userid;

		if(defined('__UC_ENV') && (__UC_ENV == 'TEST' || __UC_ENV == 'DEV'))
		{
			$this->_apcttl = 60;
			$this->_mcttl = 604800;
		}else{
			$this->_apcttl = 60;	//one minute
			$this->_mcttl = 604800;	//one week
		}
	}

	function setUserId($userid)
	{
		$this->_userid = $userid;
	}

	private function _get()
	{
		//read from memcache
		$cachekey = 'apppanel_panellist' . $this->_userid;
		$cache = new UCLibCache('apppanel');
		$applist = $cache->read($cachekey);
		if(false === $applist && 'NULL' !== $applist){
			$pdo = UCLibPDOFactory::getPDO('apppanel_panellist', $this->_userid, "store2dbconfig");
			$applist = $pdo->query_one_with_prepare("SELECT applist FROM $pdo->database.$pdo->table WHERE userid = ?", array($this->_userid));
			if(false === $applist)
				return false;
	
			if(!empty($applist))
			{
				$tmp = explode(',', $applist);
				$applist = array();
				foreach($tmp as $appid)
				{
					$applist[$appid]['id'] = $appid;
				}
			}
			//TODO: write cache
			$cache->write($cachekey, $applist, $this->_mcttl);
		}
		$this->_doWhiteList(&$applist);
		$this->_doBlackList(&$applist);
		return $applist;
	}

	public function set($applist)
	{
		return $this->_set($applist);
	}

	private function _set($applist)
	{
		if(0 == count($applist))
			return false;

		$tmp = '';
		foreach($applist as $key => $val)
		{
			$tmp .= (!empty($tmp) ? ',' : '') . $val['id'];
		}

		$pdo = UCLibPDOFactory::getPDO('apppanel_panellist', $this->_userid, "store2dbconfig");
		$ret = $pdo->exec_with_prepare("UPDATE $pdo->database.$pdo->table SET applist = ?, uptime = CURRENT_TIMESTAMP WHERE userid = ?", array($tmp, $this->_userid));
		if(false === $ret)
			return false;

		if(1 != $ret)
		{
			$ret = $pdo->exec_with_prepare("INSERT INTO $pdo->database.$pdo->table SET userid = ?, applist = ?, uptime = CURRENT_TIMESTAMP", array($this->_userid, $tmp));
			if(false === $ret || 1 != $ret)
				return false;
		}

		$cachekey = 'apppanel_panellist' . $this->_userid;
		$cache = new UCLibCache('apppanel');
		$cache->delete($cachekey);

		return true;
	}

	/**
	 * 判断用户是否安装了应用
	 *
	 * @param int $appid
	 * @return bool
	 */
	public function existApp($appid)
	{
		$applist = $this->_get();
		if(false == $applist)
			return false;
		if(isset($applist[$appid]))
			return true;

		return false;
	}

	/**
	 * 获取应用面板数据
	 * 
	 * @return array false for fail
	 */
	public function get($without_info = false)
	{
		$applist = $this->_get();
		if(false === $applist)
			return false;

		if($without_info)
		{
			return $applist;
		}else{
			return $this->_store->getApps($applist);
		}
	}

	public function add($appid)
	{
		if(!is_numeric($appid))
			return false;

		$applist = $this->_get();
		if(false === $applist)
			return false;

		if(isset($applist[$appid]))
			return false;
		else{
			$applist[$appid]['id'] = $appid;
			return $this->_set($applist);
		}
	}

	/**
	 * 将白名单应用插入面板
	 *
	 * @return 
	 */
	private function _doWhiteList(&$applist)
	{
		$panel_whitelist = UCModStore::getInstance()->getConfig('panel_whitelist');
		if(empty($panel_whitelist))
			return;

		$panel_whitelist = explode(',', $panel_whitelist);
		foreach($panel_whitelist as $appid)
		{
			if(!isset($applist[$appid]))
				$applist[$appid]['id'] = $appid;
		}
	}

	/**
	 * 删除面板中包含于黑名的应用
	 *
	 * @return 
	 */
	private function _doBlackList(&$applist)
	{
		if(0 == count($applist))
			return;

		$panel_blacklist = UCModStore::getInstance()->getConfig('panel_blacklist');
		if(empty($panel_blacklist))
			return;

		$panel_blacklist = explode(',', $panel_blacklist);
		foreach($panel_blacklist as $appid)
		{
			if(isset($applist[$appid]))
			{
				unset($applist[$appid]);
				break;
			}
		}

		return;
	}

	public static function getIcon($appid, $tag = '50', $justsrc = true)
	{
		$app = UCModStore::getInstance()->getApp($appid);
		$ver = 0;

		if($app && isset($app['ext']) && is_array($app['ext'])) {
			$ver = $app['ext']["iconver"];
		}

		$suffix = 'png';
		
		if($tag > '50')
		{
			$suffix = 'jpg';
		}

		$dir = "";
		
		if ($ver) {
			$dir = substr(md5($appid),0,3).'/';
			$src = 'http://' . (defined('__UC_ENV') && __UC_ENV == 'DEV' ? 'dev.' : '') . 'f.staticsdo.com/appicons/' .$dir . $appid . '_' . $tag .'.'. $suffix. "?$ver";
		} else {
			$src = 'http://' . (defined('__UC_ENV') && __UC_ENV == 'DEV' ? 'dev.' : '') . 'ipic.staticsdo.com/v1/appicons/' . $appid . '_' . $tag .'.'. $suffix;
		}
		if($justsrc)
			return $src;
		else
			return '<img src="' . $src . '" border="0" />';
	}

	//解析APP实际链接地址
	public static function getLink(&$app, $justlink = false)
	{
		if(isset($app['ext']['norewrite']) && $app['ext']['norewrite'] == 1)
		{
			$link = $app['link'];
		}else if(isset($app['ext']['comingsoon']) && $app['ext']['comingsoon'] == 1){
			$link = '/store/comingsoon';
		}else{
			$link = '/store/app/id/' . $app['id'];
		}

		if($justlink)
			return $link;

		$link = 'href="' . $link . '"';

		if(isset($app['ext']['target']))
		{
			$link .= ' target="' . $app['ext']['target'] . '"';
		}

		return $link;
	}

	//extened function //////////////////////////////////////////
	//生产一个可以在应用页面内部转向的url
	public static function getIframeRedirectLink(&$app, $link){
		$ori_link = self::getLink(&$app, true);
		return $ori_link . '?link=' . urlencode($link) . '&token=' . md5($link . UCConfStore::$iframe_redirect_key);
	}

	//验证url有效性
	public static function checkIframeRedirectLink($link, $token){

		$token2 = md5($link . UCConfStore::$iframe_redirect_key);
		return ($token2 === $token);
	}
}